<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Assembly Name="Microsoft.SharePoint.ApplicationPages, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
    Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Import Namespace="System.Diagnostics" %>

<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" EnableViewState="false"
    EnableViewStateMac="false" %>

<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<asp:Content ID="Content4" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
    <SharePoint:EncodedLiteral ID="EncodedLiteral2" runat="server" Text="Delete Items"
        EncodeMethod='HtmlEncode' />
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea"
    runat="server">
    <SharePoint:EncodedLiteral ID="EncodedLiteral1" runat="server" Text="Delete Items from a Custom List"
        EncodeMethod='HtmlEncode' />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="PlaceHolderPageDescription" runat="server">
    <SharePoint:EncodedLiteral ID="EncodedLiteral3" runat="server" Text="Use this page to delete items from a Custom List"
        EncodeMethod='HtmlEncode' />
</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <br />
    <br />
    <asp:Label ID="lblItemToDeleteList" runat="server"></asp:Label>
    <br />
    <br />
    <asp:LinkButton ID="Button1" runat="server" Text="Delete Items" OnClick="DeleteItems" />
    <input type="hidden" runat="server" id="listid" />

    <script runat="server" id="Server-PageLoad">
        
        //TODO: The table should be sortable
        //TODO: The table should be paginable

        string breadCrumbListLink = string.Empty;
        string breadCrumbWebLink = string.Empty;
        string listUrl = string.Empty;
        SPList aList = null;
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                //Response.Write(Request.QueryString["id"].ToString());
                //hiding Delete Items button since no items to delete are displayed. 
                Button1.Visible = false;

                //provisioning bread crumb
                using (SPWeb myWeb = SPContext.Current.Web)
                {
                    //get the list ID stored before Postback
                    aList = myWeb.Lists[new Guid(listid.Value)];
                    listUrl = SPUrlUtility.CombineUrl(myWeb.Url, aList.RootFolder.Url);
                    //server side step to provision the bread crumb. 
                    breadCrumbWebLink = "<a href='" + myWeb.Url + "'>" + myWeb.Title + "</a>";
                    breadCrumbListLink = "<a href='" + listUrl + "'>" + aList.Title + "</a>";
                }
                return;
            }

            using (SPWeb myWeb = SPContext.Current.Web)
            {
                SPList aList = null;
                SPView aListDefaultView = null;
                try
                {
                    aList = myWeb.Lists[new Guid(Request.QueryString["id"])];

                    //provisioning bread crumb
                    listUrl = SPUrlUtility.CombineUrl(myWeb.Url, aList.RootFolder.Url);
                    Debug.WriteLine("deleteitem.aspx listUrl :" + listUrl);
                    breadCrumbWebLink = "<a href='" + myWeb.Url + "'>" + myWeb.Title + "</a>";
                    breadCrumbListLink = "<a href='" + listUrl + "'>" + aList.Title + "</a>";

                    //Getting the default view of the list in order to display only the Fields displayed in th default view. 
                    foreach (SPView aView in aList.Views)
                    {
                        if (aView.DefaultView)
                        {
                            aListDefaultView = aView;
                        }
                    }

                    //storing the list ID to be retrieved after Postback in order to build bread crumb. 
                    listid.Value = aList.ID.ToString();
                }
                catch
                {
                    lblItemToDeleteList.Text = "The list does not exist. Check that the page URL is correct and has not been manualy modified.";
                    Button1.Visible = false;
                    return;
                }

                //starting building the table
                string result = string.Empty;
                result = "\n\t<table style='border-collapse:collapse;width:100%'>";

                //retrieving  fields displayed in the default view by using the default view xml schema
                System.Xml.XmlDocument myXmlDoc = new System.Xml.XmlDocument();
                myXmlDoc.LoadXml(aListDefaultView.SchemaXml);

                System.Xml.XmlNodeList DisplayedFieldsNodesList = myXmlDoc.SelectNodes("//ViewFields/FieldRef");
                int fieldsNumber = DisplayedFieldsNodesList.Count;
                int cellNumber = fieldsNumber;
                //int width = 100 / (cellNumber);
                //string strWidth = width.ToString() + " %";

                string row1 = "\n\t\t<tr><td style='padding:2px' collspan='" + cellNumber + "'>" + "<img src='/_layouts/images/blank.gif' width='1px' height='3px'></td></tr>"; //aList.BaseType.ToString() +
                string row2 = "\n\t\t<tr><td style='padding:0px' collspan='" + cellNumber + "' class='ms-sectionline'>" + "<img src='/_layouts/images/blank.gif' width='1px' height='1px'></td></tr>"; //aList.BaseType.ToString() +;        
                string row3 = "\n\t\t<tr><td class='ms-sectionheader ms-descriptiontext' nowrap style='background-color:#ddd'><h3 class='ms-standardheader'><input type='checkbox' onclick='JavaScript:selectAll(this.id);' id='ckbxAll' />&nbsp;" + aList + "</h3></td>";

                //Response.Write("\n\n"+ aListdefaultview.SchemaXml + "\n\n");//if you want to see the view
                //schema of the list by viewing the HML source code of the displayed page. 

                //building the Table Header with the name of the fields displayed in the default view
                string aDisplayedField = string.Empty;
                foreach (System.Xml.XmlNode aNode in DisplayedFieldsNodesList)
                {
                    aDisplayedField = aNode.Attributes["Name"].Value;
                    if (aDisplayedField == "LinkTitle")
                    {
                        //aDisplayedField = "Title";//I don't display the Title anymore since I have already got it
                        //by calling the Item Name
                        continue;
                    }

                    //to avoid displaying attachment column
                    //if (aDisplayedField == "Attachments")
                    //{
                    //    continue;
                    //}

                    row3 += "<td  class='ms-descriptiontext' style='background-color:#dddddd;border-top:solid 2px #ddd' >" + aDisplayedField.Replace("_x0020_", " ") + "</td>";
                }

                result += row1;
                result += row2;
                result += row3 + "</tr>";

                string row4 = "\n\t\t<tr><td style='padding:2px' collspan='" + cellNumber + "' >" + "<img src='/_layouts/images/blank.gif' width='1px' height='3px'></td></tr>"; //aList.BaseType.ToString() +
                result += row4;

                //building the Table Body 
                string rowN = string.Empty;
                foreach (SPListItem myItem in aList.Items)
                {
                    rowN = "\n\t\t<tr><td class='ms-descriptiontext'  style='padding-bottom:2px;vertical-align:middle;' nowrap >" + "<input  type='checkbox' id='" + myItem.ID + "' name='ckbx_" + aList + "_" + myItem.ID + "' onclick='JavaScript:checkClickAll()' />&nbsp;" + myItem.Name.Trim() + "&nbsp;</td>";

                    foreach (System.Xml.XmlNode aNode in DisplayedFieldsNodesList)
                    {
                        aDisplayedField = aNode.Attributes["Name"].Value;
                        string value = string.Empty;

                        switch (aDisplayedField)
                        {
                            case "LinkTitle":
                                continue;

                            case "Attachments":
                                //to avoid displaying attachments
                                //continue;
                                if (myItem[aDisplayedField].ToString() == "True")
                                {
                                    value = "<a style='text-decoration:none;' href='" + listUrl + "/Attachments/" + myItem.ID + "/" + myItem.Attachments[0] + "' >" + myItem.Attachments[0] + "</a>";
                                }
                                break;

                            default:
                                if (myItem[aDisplayedField] == null)
                                {
                                    value = "&nbsp;";
                                }
                                else
                                {
                                    value = myItem[aDisplayedField].ToString().Trim();
                                }
                                break;
                        }

                        rowN += "<td  class='ms-descriptiontext' style='margin-right:5px;color:black;border:solid 0px gray' nowrap >" + value + "</td>";
                    }
                    result += rowN + "</tr>";
                }
                result += "\n\t</table>\n";
                lblItemToDeleteList.Text = result;
            }
        }
    </script>

    <script runat="server" id="Server-DeleteItems">
        public void DeleteItems(object sender, EventArgs e)
        {
            try
            {
                //in Postback, we delete the items (in fact we recycle them, we place them in the site recycle bin)
                if (IsPostBack)
                {
                    string toDeleteInList = string.Empty;
                    string toDeleteItemID = string.Empty;
                    SPList myList = null;
                    SPListItem myItem = null;

                    using (SPWeb myWeb = SPContext.Current.Web)
                    {
                        for (int i = 0; i < Request.Form.Count; i++)
                        {
                            //Response.Write(Request.Form.Keys[i] + " __ " + Request.Form[i] + "<br>");
                            if (Request.Form.Keys[i].Contains("ckbx"))
                            {
                                char[] separator = { '_' };
                                //we instantiate SPList only once
                                if (myList == null)
                                {
                                    toDeleteInList = Request.Form.Keys[i].Split(separator)[1];
                                    myList = myWeb.Lists[toDeleteInList];
                                }

                                toDeleteItemID = Request.Form.Keys[i].Split(separator)[2];

                                myItem = myList.GetItemById(Convert.ToInt32(toDeleteItemID));
                                myItem.Recycle();
                            }
                        }
                    }
                }

                lblItemToDeleteList.Text = "Your items were deleted successfuly.";

            }
            catch (Exception ex)
            {
                string result = string.Empty;

                result += "<span style='color:red'>An error occured during the process. Your Items might be not all deleted.</span>";
                //result += ex;
                lblItemToDeleteList.Text = result;
            }
        }
    </script>

    <script runat="server" id="Server-RenderChildren">
        protected override void RenderChildren(HtmlTextWriter output)
        {
            LiteralControl myBreadcrumb = new LiteralControl(breadCrumbWebLink + " > " + breadCrumbListLink);
            Master.FindControl("PlaceHolderTitleBreadcrumb").FindControl("ContentMap").Controls.Add(myBreadcrumb);
            base.RenderChildren(output);
        }

    </script>

    <script type="text/javascript" id="Client-CheckBoxes DHTML">
        //This javaScript code manages the:
        // select all items
        // unselect all items 
        var myCheckBoxAll;
        function selectAll(id) {

            myCheckBoxAll = document.getElementById(id);

            var Check = false;

            Check = myCheckBoxAll.checked;

            var errorsMessage = "<br>" + Check;
            var myInputControls = document.getElementsByTagName("INPUT");

            for (i = 0; i < myInputControls.length; i++) {

                if (myInputControls[i].id == id) {
                    continue;
                }

                try {//there is an error since not all input controls have a type property
                    if (myInputControls[i].type == "checkbox") {
                        //errorsMessage += '<br>' + myInputControls[i].id;
                        //errorsMessage += '<br>' + Check;
                        if (Check == false) {
                            myInputControls[i].checked = false;
                            //errorsMessage += '<br>false ' + myInputControls[i].id;
                        } else {
                            myInputControls[i].checked = true;
                            //errorsMessage += '<br>true ' + myInputControls[i].id;
                        }
                    }
                } catch (Error) {
                    errorsMessage += '<br>' + Error.message;
                }
            }
            //document.getElementById('lblmessage').innerHTML = errorsMessage;

        }

        function checkClickAll() {

            if (myCheckBoxAll) {
                if (myCheckBoxAll.checked) {

                    myCheckBoxAll.checked = false;
                }
            }
        }
    </script>

    <div id="lblmessage" />
</asp:Content>
